from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.generics import ListAPIView, GenericAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.filters import OrderingFilter
from drf_haystack.viewsets import HaystackViewSet
# Create your views here.
from goods.models import GoodsCategory, SKU
from goods.serializers import SKUSearchSeializer, SKUSSerialziers, SKUHistorySerialzier
from goods.utils import PageNum, ListPageNum


class CategoriesView(APIView):

    # 面包屑导航分类数据获取
    def get(self, request, pk):

        # 1.获取三级分类id
        # 2.查询三级分类对象
        cat3 = GoodsCategory.objects.get(id=pk)

        # 3.通过三级分类对象获取二级分类
        cat2 = cat3.parent

        # 4.通过二级分类获取一级分类
        cat1 = cat2.parent

        # 5.返回结果
        return Response({
            'cat1': cat1.name,
            'cat2': cat2.name,
            'cat3': cat3.name,
        })


class SKUSView(ListAPIView):
    """
    获取当前分类的所有商品
    1.获取分类id
    2.查询属于这个分类的所有对象
    3.序列化返回对象
    分页和排序
    """

    # 序列化器
    serializer_class = SKUSSerialziers
    # 查询集
    # queryset = SKU.objects.filter(id=pk)
    # 分页序列化器
    pagination_class = PageNum
    # 查询过滤器
    filter_backends = [OrderingFilter]
    ordering_fields = ('create_time', 'sales', 'price')

    def get_queryset(self):

        pk = self.kwargs['pk']
        return SKU.objects.filter(category_id=pk)


class SKUSearchView(HaystackViewSet):

    index_models = [SKU]

    serializer_class = SKUSearchSeializer

    pagination_class = PageNum


class SKUHistoryView(CreateAPIView, ListAPIView):
    """
        用户浏览历史记录
    """

    # serializer_class = SKUHistorySerialzier


    def get_queryset(self):
        # 1、获取用户
        user=self.request.user
        # 2、建立缓存连接
        conn=get_redis_connection('history')
        # 3、查询缓存数据获取到sku——id
        sku_ids=conn.lrange('history_%s'%user.id,0,100)
        # 4、根据sku——id查询商品对象
        skus=SKU.objects.filter(id__in=sku_ids)  # [1,2,3]
        return skus

    def get_serializer_class(self):
        # 不同请求反活力不同序列化器
        if self.request.method == "POST":
            return SKUHistorySerialzier

        else:
            return SKUSSerialziers


class SKUOrderListView(ListAPIView):

    # 序列化器
    serializer_class = SKUSSerialziers
    # 分页查询器
    pagination_class = ListPageNum

    def get_object(self):
        sku = SKU.objects.all()
        return sku




